/**
 * Created by TomSean on 2017/4/11.
 */
var MonthCardManager = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
MonthCardManager.prototype = {
    init : function() {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'search_data', fs : this.findData},
            {fName : 'reset_btn', fs : this.resetInfo}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:_this.$parent.find('#trafficPermitCategory'), parentModelKey:BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT}, _this);
        JsonpAjax(baseApiPath + 'traffic_permit/types/dropdown', undefined, 'json', function(res) {
            var data = [];
            data.push({id:'', trafficPermitName:'--请选择--'})
            for (var i = 0; i < res.length; i++) {
                data.push(res[i]);
            }
            var ddl = _this.$parent.find('#trafficPermitType').kendoDropDownList({
                dataTextField: "trafficPermitName",
                dataValueField: "id",
                dataSource: data
            }).data('kendoDropDownList');
            ddl.select(0);
        });
        this.initTable();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
    },
    findData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var params = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        if(!isEmpty(params["beginDate"])){
            params["beginDate"] = params["beginDate"].pattern("yyyy-MM-dd");
        }
        if(!isEmpty(params["endDate"])){
            params["endDate"] = params["endDate"].pattern("yyyy-MM-dd");
        }
        var data = {jsonParam : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({
            url : baseApiPath + 'charges_log/list',
            data : data,
            dataType : 'odata'
        });
        var grid = _this.$parent.find('#month_card_top_up_data_list').data('kendoGrid');
        grid.setDataSource(dataSource);
    },
    initTable : function() {
        var _this = this;
        var columns = [
            {
                width: 30,
                headerTemplate: '<input type="checkbox" gridId="month_card_top_up_data_list" onclick="gridCheckAll(this)" />',
                template: '<input type="checkbox" value="${id}" name="charges_log_id" />'
            },
            {
                width : 200,
                title : '通行证ID',
                field : 'trafficPermitInfo.uniqueIdentifier'
            },
            {
                width : 80,
                title : '通行证类别',
                template:"#:Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, trafficPermitInfo.trafficPermitCategory)#"
            },
            {
                width : 80,
                title : '通行证类型',
                field : 'trafficPermitType.trafficPermitName'
            },
            {
                width : 80,
                title : '充值金额',
                field : 'chargeMoney'
            },
            {
                title : '有效日期',
                template : '#:beginTime# ～ #:endTime#'
            },
            {
                width : 80,
                title : '车牌号',
                field : 'trafficPermitInfo.vehicleNo'
            },
            {
                title : '车主姓名',
                field : 'trafficPermitInfo.pbaOwnerInfoByOwnerCode.ownerName'
            },
            {
                title : '收费方式',
                template : '#:Utils.getModelNameByParentKey(BASIS.CHARGE_METHOD.ROOT, chargeMethod)#'
            },
            {
                title : '支付类型',
                template : '#:Utils.getModelNameByParentKey(BASIS.PAY_TYPE.ROOT, payType)#'
            },
            {
                title : '操作人',
                field : 'chargeUserid'
            }
        ];
        this.sysUtils.createGird(this.$parent.find('#month_card_top_up_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnsMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find('input[type=checkbox]').val();
                });
                _this.selectRowId = selected[0];
            }
        });
    },
    openPrePaidWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.preDiv = _this.sysUtils.openWindow(_this.preDiv, {
            title : '充值实体卡',
            height : "680px",
            width : "900px",
            resizable : false,
            content : 'views/parkLotCenter/topUpPayment/monthCardTopUpPrePaid.html',
            close : function(e) {
                clearInterval(chargesLogPrePaid.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
            }
        }, true);
    },
    openPrePaidVisualWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.preDiv = _this.sysUtils.openWindow(_this.preDiv, {
            title : '充值虚拟卡',
            height : "680px",
            width : "900px",
            resizable : false,
            content : 'views/parkLotCenter/topUpPayment/monthCardTopUpPrePaidVisual.html',
            close : function(e) {
                clearInterval(chargesLogPrePaid.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
            }
        }, true);
    }
};

var ChargesLogPrePaid = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
var devInfos = [];
ChargesLogPrePaid.prototype = {
    init : function() {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'check_device', fs : this.checkDevice},
            {fName : 'start_read', fs : this.startRead},
            {fName : 'single_pre_paid', fs : this.singlePrePaid},
            {fName : 'batch_pre_paid', fs : this.batchPrePaid}
        ];
        this.ws = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, this.$parent);
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        this.$parent.find('#beginTime').kendoDatePicker({
            change : function() {
                _this.load$beginTime = this.value().pattern("yyyy-MM-dd");
                _this.loadPreferential();
                _this.calMonth();
            }
        });
        var months = [{'text':'一个月', value:1},{'text':'两个月', value:2},{'text':'三个月', value:3},{'text':'四个月', value:4},{'text':'五个月', value:5},{'text':'六个月', value:6},{'text':'七个月', value:7},{'text':'八个月', value:8},{'text':'九个月', value:9},{'text':'十个月', value:10},{'text':'十一个月', value:11},{'text':'一年', value:12},{'text':'两年', value:24},{'text':'三年', value:36}];
        var selectMonthDropDownList = this.$parent.find('#selectMonth').kendoDropDownList({
            dataTextField: "text",
            dataValueField: "value",
            dataSource: months,
            select : function(e) {
                var valMonth = this.dataItem(e.item).value;
                _this.selectMonth = valMonth;
                _this.calMonth();
            }
        }).data('kendoDropDownList');
        selectMonthDropDownList.select(0);
        this.selectMonth = selectMonthDropDownList.dataItem(0).value;
        /*  获取外接设备信息 */
        JsonpAjax(baseApiPath + "externalDevice/device_info/ic", undefined, 'json', function(res) {
            var list = res;
            if (devInfos.length > 0) {
                devInfos = new Array();
            }
            for (var i = 0; i < list.length; i++) {
                devInfos.push(list[i]);
            }
            var devices = _this.$parent.find('#device').kendoDropDownList({
                dataTextField : "deviceName",
                dataValueField : "deviceCode",
                dataSource : devInfos,
                change:function(e){
                    _this.checkDeviceStatus = 0;
                }
            }).data('kendoDropDownList');
            devices.select(0);
        }, true);

        //////////////////////////////////////////////////////////////////////////////
        JsonpAjax(baseApiPath + 'traffic_permit/types/dropdown', undefined, 'json', function(res) {
            var data = [];
            for (var i = 0; i < res.length; i++) {
                data.push(res[i]);
            }
            var ddl = _this.$parent.find('#trafficType').kendoDropDownList({
                dataTextField: "trafficPermitName",
                dataValueField: "id",
                dataSource: data,
                index:0,
                change : function () {
                    var dataItem = this.dataItem();
                    _this.$parent.find('#balance').val(dataItem.payMoney);
                    _this.calcMoney();
                }
            }).data('kendoDropDownList');
            ddl.select(0);
            var dataItem = ddl.dataItem();
            _this.$parent.find('#balance').val(dataItem.payMoney);
            _this.calcMoney();
        }, true);
        Utils.createDataDictDropDownList({
                div:this.$parent.find('#category'),
                parentModelKey:BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT,
                select:Utils.getModelValueByModelKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ENTITY)
            }, this);
        this.loadPreferential();
        this.loadInfo();
        this.calcMoney();
    },
    startRead : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.timerRead = setInterval(function() {
            _this.readCard();
        }, 1000);
    },
    loadPreferential : function() {
        var _this = this;
        var dataT = {beginTime : this.load$beginTime, endTime : this.load$endTime};
        JsonpAjax(baseApiPath + "preferential/valid", dataT, "json", function(res) {
            var data = [];
            for (var i = 0; i < res.length; i++) {
                data.push(res[i]);
            }
            if (data.length < 1) {
                data.push({preferentialCode : -1, preferentialName:"暂无可用优惠"});
            }
            if (data.length > 0) {
                var dd = _this.$parent.find('#preferential').kendoDropDownList({
                    dataTextField: "preferentialName",
                    dataValueField: "preferentialCode",
                    dataSource : data,
                    change : function(e) {
                        var preferential = this.dataItem();
                        var type = preferential.preferentialType;
                        _this.calcType = type;
                        _this.calcValue = preferential.preferentialContent;
                        _this.calcMoney();
                    }
                }).data('kendoDropDownList');
                var preferential = dd.dataItem(dd.select());
                var type = preferential.preferentialType;
                _this.calcType = type;
                _this.calcValue = preferential.preferentialContent;
                _this.calcMoney();
            }
        });
    },
    calcMoney : function() {
        var _this = this;
        var type = _this.calcType;
        var val = _this.calcValue;
        var calc, sourceMoney, resultMoney;
        sourceMoney = _this.$parent.find('#balance').val();
        if (sourceMoney.charAt(sourceMoney.length-1) == '.') {
            sourceMoney = parseFloat(sourceMoney.substring(0, sourceMoney.length-1));
        }
        if (type == 0 /* 0抵用现金 */) {
            resultMoney = sourceMoney - val;
            if (resultMoney <= 0) {
                resultMoney = 0;
            }
            _this.$parent.find('#calc').html(' 优惠 '+val+'元&nbsp;');
        } else if (type == 1 /* 1折扣 */) {
            resultMoney = sourceMoney * val;
            _this.$parent.find('#calc').html(' 打 '+ (val*10)+'折');
        } else {
            resultMoney = sourceMoney;
            _this.$parent.find('#calc').html('');
        }
        resultMoney = resultMoney + '';
        if (resultMoney.indexOf('.') != -1) {
            /* 如果输入为小数，则保留最后2位 */
            var temp = resultMoney.substring(resultMoney.indexOf('.')+1);
            if (temp.length > 2) {
                temp = temp.substring(0, 2);
                resultMoney = resultMoney.substring(0, resultMoney.indexOf('.'));
                resultMoney = resultMoney + '.' + temp;
            }
        }
        _this.$parent.find('#sourceMoney').html(sourceMoney);
        _this.$parent.find('#resultMoney').html(resultMoney);
    },
    calMonth : function() {
        var beginTime = new Date(this.$parent.find('#beginTime').val());
        var endTime = new Date(this.$parent.find('#beginTime').val());
        endTime.setMonth(beginTime.getMonth() + this.selectMonth);
        if (beginTime.getDate() != endTime.getDate()) {
            endTime.setDate(beginTime.getDate()-(endTime.getDate()));
            endTime.setMonth(endTime.getMonth()-1);
        } else {
            var beginDate = new Date(beginTime.getFullYear(), beginTime.getMonth()+1, 0);
            var endDate = new Date(endTime.getFullYear(), endTime.getMonth()+1, 0);
            if (beginDate.getDate() == beginTime.getDate() && endDate.getDate() != endTime.getDate()) {
                endTime.setDate(endDate.getDate());
            }
        }
        //this.$parent.find('#endTime').val(endTime.pattern("yyyy/M/d"));
        this.sysUtils.mvvmModel.set('endTime', endTime);
    },
    loadInfo : function() {

    },
    openSuccess : function(e) {
        console.log('与后台建立通信正常！');
    },
    onClose : function(e) {
        notification({title : "读卡设备异常", message : "连接断开，请检查设备、网络是否正常，再重新尝试读卡"}, 'info');
        clearInterval(chargesLogPrePaid.timerRead);
    },
    handlerMessage : function(e) {
        var data = JSON.parse(e.data);
        var $status = $('#readCardStatus');
        if (data.msgType == "REPLY" && data.replyType == "success") {
            if (!isEmpty(chargesLogPrePaid.readCardSerializeNumber) && chargesLogPrePaid.readCardSerializeNumber==data.serialNumber) {
                var result = JSON.parse(data.replayMsg);
                var phyid = result.phyid;//物理卡号
                var cardsno = result.cardsno;//逻辑卡号
                // 读卡成功时
                if (result.opstatus == 1) {
                    if (!isEmpty(chargesLogPrePaid.phyid) && chargesLogPrePaid.phyid != phyid) {
                        if (chargesLogPrePaid.noticeMessage == '当前卡与读卡信息不同，请换会读卡时的磁卡再操作') {
                            return;
                        }
                        chargesLogPrePaid.noticeMessage = '当前卡与读卡信息不同，请换会读卡时的磁卡再操作';
                        notification({title : '操作失败', message : '当前卡与读卡信息不同，请换会读卡时的磁卡再操作'}, 'info');
                        return;
                    }
                    if (cardsno == '0') {
                        if (chargesLogPrePaid.noticeMessage == '此卡未发行，不能充值') {
                            return;
                        }
                        chargesLogPrePaid.noticeMessage = '此卡未发行，不能充值';
                        notification({title : '操作失败', message : '此卡未发行，不能充值'}, 'info');
                        $status.css({"color":"red"});
                        $('#readCardStatus').html('此卡未发行，不能充值');
                        return;
                    }
                    if (chargesLogPrePaid.phyid == phyid) {
                        return;
                    }
                    chargesLogPrePaid.noticeMessage = undefined;
                    chargesLogPrePaid.phyid = phyid;
                    $status.css({"color":"green"});
                    $status.html(phyid);
                    chargesLogPrePaid.readCardStatus = 1;
                    chargesLogPrePaid.$parent.find('#phyid').val(phyid);
                    chargesLogPrePaid.$parent.find('#rationUniqueIdentifier').val(cardsno);
                    var dataT = { 'cardno' : cardsno }
                    JsonpAjax(baseApiPath + 'traffic_permit/info/owner_type', JSON.stringify(dataT), 'json', function(res) {
                        var card = res[0];
                        if (isEmpty(card)) {
                            notification({title : '数据异常', message : '此卡数据异常，请核对是否为本停车场通行证'}, 'info');
                            return;
                        }
                        clearInterval(chargesLogPrePaid.timerRead);
                        chargesLogPrePaid.$parent.find('#uniqueIdentifier').val(card.uniqueIdentifier);

                        chargesLogPrePaid.$parent.find('#category').val(card.trafficPermitCategory);
                        chargesLogPrePaid.$parent.find('#beginTime').val(card.endTime);
                        chargesLogPrePaid.calMonth();
                        chargesLogPrePaid.$parent.find('#spaceNumber').val(card.spaceNumber);
                        chargesLogPrePaid.$parent.find('#vehicleNo').val(card.vehicleNo);
                        chargesLogPrePaid.$parent.find('#phyid').val(card.physicNumber);
                        chargesLogPrePaid.$parent.find('#rationUniqueIdentifier').val(card.rationUniqueIdentifier);
                        chargesLogPrePaid.$parent.find('#printingNo').val(card.printingNo);
                        chargesLogPrePaid.$parent.find('#trafficType').val(card.crTrafficPermitType.id);

                        chargesLogPrePaid.$parent.find('.search_owner_info').val(card.pbaOwnerInfoByOwnerCode.ownerCode);
                        chargesLogPrePaid.$parent.find('.no-1-ownerName').html(card.pbaOwnerInfoByOwnerCode.ownerName);
                        chargesLogPrePaid.$parent.find('.no-1-organization').html(card.pbaOwnerInfoByOwnerCode.organization.organizationName);
                        chargesLogPrePaid.$parent.find('.no-1-ownerPhone').html(card.pbaOwnerInfoByOwnerCode.ownerPhone);
                        chargesLogPrePaid.$parent.find('.no-1-ownerAddress').html(card.pbaOwnerInfoByOwnerCode.ownerAddress);

                        if (card.masterCardFlag == 1) {
                            $('#master_card_ext_info').fadeIn('slow');
                            JsonpAjax(baseApiPath + 'traffic_permit/' + card.parent, undefined, 'json', function(res) {
                                chargesLogPrePaid.$parent.find('#master_card_uniqueIdentifier').val(res.uniqueIdentifier);
                                chargesLogPrePaid.$parent.find('#master_card_category').val(Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, res.trafficPermitCategory));
                                chargesLogPrePaid.$parent.find('#master_card_type').val(res.crTrafficPermitType.trafficPermitName);
                                chargesLogPrePaid.$parent.find('#master_card_ownerName').val(res.pbaOwnerInfoByOwnerCode.ownerName);
                                chargesLogPrePaid.$parent.find('#master_card_vehicleNo').val(res.vehicleNo);
                                chargesLogPrePaid.$parent.find('#master_card_ownerPhone').val(res.pbaOwnerInfoByOwnerCode.ownerPhone);
                                chargesLogPrePaid.$parent.find('#master_card_printingNo').val(res.printingNo);
                                $('#master_card_ext_info')[0].style.top = '0px';
                            }, true);
                        } else {
                            chargesLogPrePaid.$parent.find('#master_card_ext_info').hide();
                            chargesLogPrePaid.$parent.find('#master_card_ext_info')[0].style.top = '-235px';
                        }
                    }, true);
                } else {
                    chargesLogPrePaid.phyid = undefined;
                    if (chargesLogPrePaid.noticeMessage == '未读取到卡信息') {
                        return;
                    }
                    chargesLogPrePaid.noticeMessage = '未读取到卡信息';
                    $status.css({"color":"red"});
                    $('#readCardStatus').html('未读取到卡信息');
                    chargesLogPrePaid.$parent.find('#phyid').val('');
                    chargesLogPrePaid.$parent.find('#rationUniqueIdentifier').val('');
                    chargesLogPrePaid.$parent.find('#uniqueIdentifier').val('');
                    chargesLogPrePaid.$parent.find('#category').val('');
                    chargesLogPrePaid.$parent.find('#beginTime').val('');
                    chargesLogPrePaid.$parent.find('#endTime').val('');
                    chargesLogPrePaid.$parent.find('#spaceNumber').val('');
                    chargesLogPrePaid.$parent.find('#vehicleNo').val('');
                    chargesLogPrePaid.$parent.find('#phyid').val('');
                    chargesLogPrePaid.$parent.find('#rationUniqueIdentifier').val('');
                    chargesLogPrePaid.$parent.find('#printingNo').val('');
                    chargesLogPrePaid.$parent.find('#trafficType').val('');

                    chargesLogPrePaid.$parent.find('.search_owner_info').val('');
                    chargesLogPrePaid.$parent.find('.no-1-ownerName').html('');
                    chargesLogPrePaid.$parent.find('.no-1-organization').html('');
                    chargesLogPrePaid.$parent.find('.no-1-ownerPhone').html('');
                    chargesLogPrePaid.$parent.find('.no-1-ownerAddress').html('');
                }
            } else if (!isEmpty(chargesLogPrePaid.checkDeviceSerializeNumber) && chargesLogPrePaid.checkDeviceSerializeNumber == data.serialNumber) {
                chargesLogPrePaid.phyid = undefined;
                // 检测设备成功时
                chargesLogPrePaid.checkDeviceStatus = 1;
                chargesLogPrePaid.checkDeviceSerializeNumber = undefined;
                var $device = chargesLogPrePaid.$parent.find('#device').data('kendoDropDownList');
                var result = $device.dataItem($device.select());
                chargesLogPrePaid.$parent.find('#deviceStatus').html(result.deviceName + ' (' + result.deviceCode + ')');
                chargesLogPrePaid.$parent.find('#deviceStatus').css({'color':'green'});
                chargesLogPrePaid.devInfo = result;
                chargesLogPrePaid.timerRead = setInterval(function() {
                    chargesLogPrePaid.readCard();
                }, 1000);
            }
        } else {
            notification({title : '提示', message : '设备异常，请检测设备是否连接或重启设备后再试'}, 'info');
            clearInterval(chargesLogPrePaid.timerRead);
            return;
        }
    },
    readCard : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkDeviceStatus != 1) {
            notification({title : '操作失败', message : '请在读卡前测试设备是否连接成功'}, 'info')
            return;
        }
        _this.readCardStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        var jna = {};
        jna["reader"] = 0; //毒头？
        jna["sector"] = 15; //扇区号
        jna["deviceCacheInfo"] = result;
        var jnaStr = JSON.stringify(jna);
        _this.readCardSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"RC").serialNumber;
    },
    checkDevice : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.checkDeviceStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceNumber)) {
            _this.$parent.find('#deviceStatus').html('请先选择一个读卡器');
            _this.$parent.find('#deviceStatus').css({'color':'red'});
            return;
        }
        var jna = {"volume":1, "voicetext" : result.deviceName + "设备已连接", "lock":0, "deviceCacheInfo":result};
        _this.devInfo = undefined;
        var jnaStr = JSON.stringify(jna);
        _this.checkDeviceSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"VC").serialNumber;
        clearInterval(_this.timerRead);
    },
    batchPrePaid : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.$batch = 1;
        _this.prePaid();
    },
    singlePrePaid : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.$batch = 0;
        _this.prePaid();
    },
    prePaid : function() {
        var _this = this;
        if (validityForm(_this.$parent)) {
            var id = _this.$parent.find('#uniqueIdentifier').val();
            var beginTime = _this.$parent.find('#beginTime').val(), endTime = _this.$parent.find('#endTime').val();
            var preferential = _this.$parent.find('#preferential').val();
            var money = _this.$parent.find('#balance').val();
            var $device = _this.$parent.find('#device').data('kendoDropDownList');
            var devInfo = $device.dataItem($device.select());
            var dataT = {'id' : id, 'beginTime' : beginTime, 'endTime' : endTime, 'preferential' : parseInt(preferential), 'money' : money, 'phyid' : _this.$parent.find('#phyid').val() , 'devInfo' : devInfo};
            JsonpAjax(baseApiPath + 'traffic_permit/prepaid', JSON.stringify(dataT), 'json', function(res) {
                if (_this.$batch == 1) {
                    notification({title : '成功', message : '此卡充值成功，请换卡其他卡片'}, 'info');
                    _this.timerRead = setInterval(function() {
                        _this.readCard();
                    }, 1000);
                } else {
                    monthCardManager.findData();
                    $('#' + monthCardManager.preDiv).data('kendoWindow').close();
                }

            });
        }
    }
}
var ChargesLogPrePaidVisual = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
ChargesLogPrePaidVisual.prototype = {
    init : function() {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'single_pre_paid', fs : this.singlePrePaid},
            {fName : 'batch_pre_paid', fs : this.batchPrePaid}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        this.$parent.find('#beginTime').kendoDatePicker({
            change : function() {
                _this.load$beginTime = this.value().pattern("yyyy-MM-dd");
                _this.loadPreferential();
                _this.calMonth();
            }
        });
        var months = [{'text':'一个月', value:1},{'text':'两个月', value:2},{'text':'三个月', value:3},{'text':'四个月', value:4},{'text':'五个月', value:5},{'text':'六个月', value:6},{'text':'七个月', value:7},{'text':'八个月', value:8},{'text':'九个月', value:9},{'text':'十个月', value:10},{'text':'十一个月', value:11},{'text':'一年', value:12},{'text':'两年', value:24},{'text':'三年', value:36}];
        var selectMonthDropDownList = this.$parent.find('#selectMonth').kendoDropDownList({
            dataTextField: "text",
            dataValueField: "value",
            dataSource: months,
            change : function(e) {
                var valMonth = this.dataItem(e.item).value;
                _this.selectMonth = valMonth;
                _this.calMonth();
            }
        }).data('kendoDropDownList');
        selectMonthDropDownList.select(0);
        this.selectMonth = selectMonthDropDownList.dataItem(0).value;
        this.$parent.find('#search_traffic_permit').kendoAutoComplete({
            minLength : 1,
            filter: "contains",
            dataTextField : "vehicleNo",
            template : "<span class='k-state-default'>#: vehicleNo# <small style='font-size:12px;color:grey'>#: pbaOwnerInfoByOwnerCode.ownerName#</small></span>",
            dataSource : {
                type : "odata",
                serverFiltering: true,
                transport : {
                    read : {
                        url : baseApiPath + "traffic_permit/search/month_card"
                    }
                }
            },
            select : function(e) {
                var dataItem = this.dataItem(e.item.index());
                _this.$parent.find('#uniqueIdentifier').val(dataItem.uniqueIdentifier);
                _this.$parent.find('#category').val(Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, dataItem.trafficPermitCategory));
                _this.$parent.find('#trafficType').val(dataItem.crTrafficPermitType.trafficPermitName);
                _this.$parent.find('#beginTime').val(dataItem.endTime);
                _this.$parent.find('#spaceNumber').val(dataItem.spaceNumber);
                _this.$parent.find('#vehicleNo').val(dataItem.vehicleNo);

                _this.$parent.find('.search_owner_info').val(dataItem.pbaOwnerInfoByOwnerCode.ownerCode);
                _this.$parent.find('.no-1-ownerName').html(dataItem.pbaOwnerInfoByOwnerCode.ownerName);
                _this.$parent.find('.no-1-organization').html(dataItem.pbaOwnerInfoByOwnerCode.organization.organizationName);
                _this.$parent.find('.no-1-ownerPhone').html(dataItem.pbaOwnerInfoByOwnerCode.ownerPhone);
                _this.$parent.find('.no-1-ownerAddress').html(dataItem.pbaOwnerInfoByOwnerCode.ownerAddress);

                if (dataItem.masterCardFlag == 1) {
                    _this.$parent.find('#master_card_ext_info').fadeIn('slow');
                    JsonpAjax(baseApiPath + 'traffic_permit/' + dataItem.parentCode, undefined, 'json', function(res) {
                        _this.$parent.find('#master_card_uniqueIdentifier').val(res.uniqueIdentifier);
                        _this.$parent.find('#master_card_category').val(Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, res.trafficPermitCategory));
                        _this.$parent.find('#master_card_type').val(res.crTrafficPermitType.trafficPermitName);
                        _this.$parent.find('#master_card_ownerName').val(res.pbaOwnerInfoByOwnerCode.ownerName);
                        _this.$parent.find('#master_card_vehicleNo').val(res.vehicleNo);
                        _this.$parent.find('#master_card_ownerPhone').val(res.pbaOwnerInfoByOwnerCode.ownerPhone);
                        _this.$parent.find('#master_card_printingNo').val(res.printingNo);
                        $('#master_card_ext_info')[0].style.top = '0px';
                    }, true);
                } else {
                    _this.$parent.find('#master_card_ext_info').hide();
                    _this.$parent.find('#master_card_ext_info')[0].style.top = '-235px';
                }
                _this.calMonth();
            },
            height : 400
        });
        //////////////////////////////////////////////////////////////////////////////
        JsonpAjax(baseApiPath + 'traffic_permit/types/dropdown', undefined, 'json', function(res) {
            var data = [];
            for (var i = 0; i < res.length; i++) {
                data.push(res[i]);
            }
            var ddl = _this.$parent.find('#trafficType').kendoDropDownList({
                dataTextField: "trafficPermitName",
                dataValueField: "id",
                dataSource: data,
                index:0,
                change : function () {
                    var dataItem = this.dataItem();
                    _this.$parent.find('#balance').val(dataItem.payMoney);
                    _this.calcMoney();
                }
            }).data('kendoDropDownList');
            ddl.select(0);
            var dataItem = ddl.dataItem();
            _this.$parent.find('#balance').val(dataItem.payMoney);
            _this.calcMoney();
        });
        this.$parent.find('#category').val(Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, Utils.getModelValueByModelKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.VIRTUAL)));
        this.loadPreferential();
        this.calcMoney();
    },
    calMonth : function() {
        var beginTime = new Date(this.$parent.find('#beginTime').val());
        var endTime = new Date(this.$parent.find('#beginTime').val());
        endTime.setMonth(beginTime.getMonth() + this.selectMonth);
        if (beginTime.getDate() != endTime.getDate()) {
            endTime.setDate(beginTime.getDate()-(endTime.getDate()));
            endTime.setMonth(endTime.getMonth()-1);
        } else {
            var beginDate = new Date(beginTime.getFullYear(), beginTime.getMonth()+1, 0);
            var endDate = new Date(endTime.getFullYear(), endTime.getMonth()+1, 0);
            if (beginDate.getDate() == beginTime.getDate() && endDate.getDate() != endTime.getDate()) {
                endTime.setDate(endDate.getDate());
            }
        }
        this.sysUtils.mvvmModel.set('endTime', endTime);
    },
    loadPreferential : function() {
        var _this = this;
        var dataT = {beginTime : this.load$beginTime, endTime : this.load$endTime};
        JsonpAjax(baseApiPath + "preferential/valid", dataT, "json", function(res) {
            var data = [];
            data.push()
            for (var i = 0; i < res.length; i++) {
                data.push(res[i]);
            }
            if (data.length < 1) {
                data.push({value : -1, text:"暂无可用优惠"});
            }
            if (data.length > 0) {
                var dd = _this.$parent.find('#preferential').kendoDropDownList({
                    dataTextField: "preferentialName",
                    dataValueField: "preferentialCode",
                    dataSource : data,
                    change : function(e) {
                        var preferential = this.dataItem();
                        var type = preferential.preferentialType;
                        _this.calcType = type;
                        _this.calcValue = preferential.preferentialContent;
                        _this.calcMoney();
                    }
                }).data('kendoDropDownList');
                var preferential = dd.dataItem(dd.select());
                var type = preferential.preferentialType;
                _this.calcType = type;
                _this.calcValue = preferential.preferentialContent;
                _this.calcMoney();
            }
        });
    },
    calcMoney : function() {
        var _this = this;
        var type = _this.calcType;
        var val = _this.calcValue;
        var calc, sourceMoney, resultMoney;
        sourceMoney = _this.$parent.find('#balance').val();
        if (sourceMoney.charAt(sourceMoney.length-1) == '.') {
            sourceMoney = parseFloat(sourceMoney.substring(0, sourceMoney.length-1));
        }
        if (type == 0 /* 0抵用现金 */) {
            resultMoney = sourceMoney - val;
            if (resultMoney <= 0) {
                resultMoney = 0;
            }
            _this.$parent.find('#calc').html(' 优惠 '+val+'元&nbsp;');
        } else if (type == 1 /* 1折扣 */) {
            resultMoney = sourceMoney * val;
            _this.$parent.find('#calc').html(' 打 '+ (val*10)+'折');
        } else {
            resultMoney = sourceMoney;
            _this.$parent.find('#calc').html('');
        }
        resultMoney = resultMoney + '';
        if (resultMoney.indexOf('.') != -1) {
            /* 如果输入为小数，则保留最后2位 */
            var temp = resultMoney.substring(resultMoney.indexOf('.')+1);
            if (temp.length > 2) {
                temp = temp.substring(0, 2);
                resultMoney = resultMoney.substring(0, resultMoney.indexOf('.'));
                resultMoney = resultMoney + '.' + temp;
            }
        }
        _this.$parent.find('#sourceMoney').html(sourceMoney);
        _this.$parent.find('#resultMoney').html(resultMoney);
    },
    batchPrePaid : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.$batch = 1;
        _this.prePaid();
    },
    singlePrePaid : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.$batch = 0;
        _this.prePaid();
    },
    prePaid : function() {
        var _this = this;
        if (validityForm(_this.$parent)) {
            var id = _this.$parent.find('#uniqueIdentifier').val();
            var beginTime = _this.$parent.find('#beginTime').val(), endTime = _this.$parent.find('#endTime').val();
            var preferential = _this.$parent.find('#preferential').val();
            var money = _this.$parent.find('#balance').val();
            var dataT = {'id' : id, 'beginTime' : beginTime, 'endTime' : endTime, 'preferential' : parseInt(preferential), 'money' : money, 'phyid' : undefined , 'devInfo' : undefined};
            JsonpAjax(baseApiPath + 'traffic_permit/prepaid', JSON.stringify(dataT), 'json', function(res) {
                if (_this.$batch == 1) {
                    notification({title : '成功', message : '此卡充值成功，请换卡其他卡片'}, 'info');
                    _this.timerRead = setInterval(function() {
                        _this.readCard();
                    }, 1000);
                } else {
                    monthCardManager.findData();
                    $('#' + monthCardManager.preDiv).data('kendoWindow').close();
                }

            });
        }
    }
};